package com.zzyl.job;

import cn.hutool.json.JSONUtil;
import com.zzyl.entity.AlertRule;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.AlertMapper;
import com.zzyl.service.AlertService;

import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertRuleJob {


    @Autowired
    private AlertService alertService;

    @Autowired
    private AlertMapper alertMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    private void alertRuleJob() {
        //查询所有的规则
        List<AlertRuleVo> allAlertRules = alertMapper.selectAllAlertRule(null, null, null);
        //判断规则是否为空
        if (ObjectUtil.isEmpty(allAlertRules)) {
            return;
        }
        //查询所有设备的数据    values里面包含所有设备   每个设备中又有对应的物模型属性
        List<Object> values = redisTemplate.opsForHash().values("devicedata");
        if (ObjectUtil.isEmpty(values)) {
            return;
        }
        //数据格式化处理
        //遍历values中的设备
        List<DeviceDataVo> allDeviceDataVos = new ArrayList<>();
        values.forEach(v -> {
            //这个list中包含的是每个设备的所有属性
            List<DeviceDataVo> list = JSONUtil.toList((String) v, DeviceDataVo.class);
            //把每个设备的所有属性都添加到allDeviceDataVos中
            allDeviceDataVos.addAll(list);
        });
        //把每个物模型属性数据拿出来进行处理
        allDeviceDataVos.forEach(deviceDataVo -> {
            alertService.alertRuleData(deviceDataVo);
        });
    }
}
